// @ts-nocheck
import { useState, useEffect } from "react";
import { message } from "antd";

/**
 * 接口数据返回前加载loading
 * @param service 接口函数
 * @param defaultParams 默认参数
 * @param initialData 初始值
 * @returns
 * request: 请求函数
 * refresh: 刷新数据
 * loading: 是否是加载中状态
 * params: 请求参数
 * data: 接口返回值
 */
export const useAsync = (service, defaultParams, initialData) => {
  const [params, setParams] = useState(defaultParams);
  const [loading, setLoading] = useState(false);
  const [data, setData] = useState(initialData);

  const request = (_params) => {
    setParams(_params);
    setLoading(true);
    service(_params)
      .then((res) => {
        setData(res.data);
      })
      .catch(e => {
        // message.error(JSON.stringify(e))
      })
      .finally(() => {
        setLoading(false);
      });
  };

  const refresh = () => {
    request(params);
  };

  useEffect(refresh, []);

  return { request, refresh, loading, params, data };
};
